package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDto;
import com.sky.dto.EmployeeLoginDto;
import com.sky.dto.EmployeeModifyPasswordDto;
import com.sky.dto.EmployeePageQueryDto;
import com.sky.entity.Employee;
import com.sky.exception.extend.AccountIsLockedException;
import com.sky.exception.extend.AccountNotFoundException;
import com.sky.exception.extend.AccountPasswordErrorException;
import com.sky.exception.extend.PasswordQuestionException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.IEmployeeService;
import com.sky.vo.EmployeeLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
@Slf4j
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录的业务层方法
     * 业务逻辑：根据为一用户名来查询
     * @param employeeLoginDto
     * @return
     */
    @Override
    public EmployeeLoginVo findByUserName(EmployeeLoginDto employeeLoginDto) {
        Employee employee = employeeMapper.selectByUserName(employeeLoginDto);
        //如果数据库为空 那么
        if (employee==null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_EXIST);
        }
        //进行md5加密后与数据库的密码开始比对
        if (!DigestUtils.md5DigestAsHex(employeeLoginDto.getPassword().getBytes()).equals(employee.getPassword())){
            throw new AccountPasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)){
            throw new AccountIsLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        EmployeeLoginVo employeeLoginVo = EmployeeLoginVo.builder()
                .id(employee.getId())
                .username(employee.getUsername())
                .name(employee.getName())
                .build();
        return employeeLoginVo;
    }

    /**
     * 注册员工业务：普通增罢了
     * @param employeeDto
     */
    @Override
    public void insert(EmployeeDto employeeDto) {
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDto,employee);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.PASSWORD_CONSTANT.getBytes()));
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询的业务层逻辑
     * @param employeePageQueryDto
     * @return
     */
    @Override
    public PageResult<Employee> findByPage(EmployeePageQueryDto employeePageQueryDto) {

        //以下并没有使用分页插件的代码

        //第一步
        // 返回数据库有多少条信息 select count(*) from employee where name =?
        //在.xml写，动态查询，且是模糊查询，并返回总条数 注意: 类型是long
        /*String name =null;
        if (employeePageQueryDto.getName()!=null){
             name ="%"+employeePageQueryDto.getName()+"%";
        }

        long total=employeeMapper.count(name);*/
        //第二步
        //先将表里数据分页，在返回表里的数据，以集合的形式
       /* Integer pageBean= employeePageQueryDto.getPage()-1;
        List<Employee> employeeList =employeeMapper.findByList(pageBean,employeePageQueryDto.getPageSize(), name);*/
        //最后一步，进行封装返回给表现层
       /* PageResult<Employee> result =new PageResult<>();
        result.setRecords(employeeList);
        result.setTotal(total);
        return result;*/

        //使用分页插件的代码
        PageHelper.startPage(employeePageQueryDto.getPage(),employeePageQueryDto.getPageSize());
        Page<Employee> employeePage=employeeMapper.queryPage(employeePageQueryDto);
        return new PageResult<>(employeePage.getTotal(),employeePage.getResult());
    }

    /**
     * 修改员工状态业务层逻辑
     * @param status
     * @param id
     */
    @Override
    public void modifyStatus(Integer status, Long id) {
       employeeMapper.upDateByStatus(status,id);
    }

    /**
     * 修改密码的业务逻辑
     * @param employeeModifyPasswordDto
     */
    @Override
    public void modifyPassword(EmployeeModifyPasswordDto employeeModifyPasswordDto) {
        //先根据旧密码来与数据库的密码比对一下，是否正确
      int num = employeeMapper.comparePassword(employeeModifyPasswordDto.getEmpId(),
              employeeModifyPasswordDto.getOldPassword());
      if(num!=1){
          //如果不为1，一般情都是0
          throw new PasswordQuestionException(MessageConstant.PASSWORD_NOT_THE_SAME);
      }
      //那么为1，进行修改
        employeeMapper.modifyPassword(employeeModifyPasswordDto);
    }

    /**
     * 根据id查询员工信息 业务层逻辑
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
       Employee employee=employeeMapper.getById(id);
       if (employee==null){
           /**-
            * 虽然这个基本上不肯能发生，只是防止测试出现问题
            */
           throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_EXIST);
       }else {
           return employee;
       }
    }

    @Override
    public void modifyEmployee(Employee employee) {
        //直接向持久层传入数据
        employeeMapper.modifyEmployee(employee);
    }
}
